const express = require('express');
const router = express.Router();
const Blog = require('../../mongoModuels/rear/blog');
const jwt = require('jsonwebtoken');


router
.post('/login', (req, res) => {
    if(req.body.userName && req.body.passWord) {
        let data = {
            name: req.body.userName,
            pass: req.body.passWord
        }
        roleData(data, req, res)
    } else {
        res.json({
            status: 0,
            message: '参数不足'
        })
    }
})


const roleData = (data, req, res) => {
    Blog.login.findOne({'username': data.name, 'password': data.pass}).populate('roleId').exec((err, data) => {
        if(err) {
            res.json({
                status: 0,
                message: '登录失败'
            })
        } else {
            let content ={username: data.username, juris: data.roleId.juris}; //token主题
            let secretOrPrivateKey="jwt"; // 加密的key（密钥）
            let token = jwt.sign(content, secretOrPrivateKey, {
                expiresIn: 60*60*24  // 1天过期
            });
            res.json({
                status: 1,
                message: '登录成功',
                data: {
                    token: token,
                    username: data.username
                }
            })
        }
    })
}

module.exports = router;